// @ts-nocheck
import * as FileSaver from 'file-saver'
import * as ExcelJs from 'exceljs/dist/exceljs'

export function export2Excel(tHeader: any[], data: any[], excelName: string) {
  const workbook = new ExcelJs.Workbook()
  workbook.creator = 'Taffe'
  workbook.lastModifiedBy = 'Taffe'
  workbook.created = new Date()
  workbook.modified = new Date()
  workbook.lastPrinted = new Date()

  const worksheet = workbook.addWorksheet(excelName)

  worksheet.columns = tHeader.map(h => {
    return { header: h.label, key: h.prop, width: 16 }
  })
  for (let h = 1; h <= worksheet.columns.length; h++) {
    worksheet.getCell(`${String.fromCharCode(64 + h)}1`).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF409eff' }
    }
  }

  worksheet.addRows(data)

  // const width = []
  for (let i = 0; i <= data.length; i++) {
    worksheet.getRow(i + 1).height = i == 0 ? 25 : 20
    for (let h = 1; h <= worksheet.columns.length; h++) {
      const cell = worksheet.getCell(`${String.fromCharCode(64 + h)}${i + 1}`)
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      }
      cell.alignment = { vertical: 'middle' }
      // let cellWidth
      // const cellData = i == 0 ? tHeader[h - 1] : data[i - 1][h - 1]
      // if (cellData != null) {
      //   if (cellData.toString().charCodeAt(0) > 255) {
      //     //中文
      //     cellWidth = cellData.toString().length * 2 + 2
      //   } else {
      //     cellWidth = cellData.toString().length + 2
      //   }
      // }
      // if (width[h - 1]) {
      //   const oldWidth = width[h - 1]
      //   if (oldWidth < cellWidth) {
      //     width[h - 1] = cellWidth
      //   }
      // } else {
      //   width.push(cellWidth)
      // }
    }
  }

  workbook.xlsx.writeBuffer().then((buffer: any) => {
    const blob = new Blob([buffer], { type: 'application/octet-stream' })
    FileSaver.saveAs(blob, `${excelName}.xlsx`)
  })
}
